<script>
import KtScrollView from "../../../uni_modules/kantboot-framework-uniapp/components/kt-scroll-view/kt-scroll-view.vue";
import KtCarousel from "../../../uni_modules/kantboot-framework-uniapp/components/kt-carousel/kt-carousel.vue";
import FpCoursePanel from "../../../components/fp-course-panel/fp-course-panel.vue";
import UserInfoCard from "../../../components/user-info-card/user-info-card.vue";
import UDivider from "../../../uni_modules/uview-ui/components/u-divider/u-divider.vue";

export default {
  name: "pageChat",
  components: {UDivider, UserInfoCard, FpCoursePanel, KtCarousel, KtScrollView},
  data() {
    return {
      // 组件高度
      height: 0,
      // 组件高度
      navBarHeight: 0,
      // 是否加载完成
      isLoad: false,
      scrollTop: 0,
      list:[]
    };
  },
  mounted() {
    // 获取导航栏高度
    // this.navBarHeight = this.$refs.navBar.getHeight();
    // 获取#navBarInMessage的高度
    this.$kt.event.on('changeTabbar', ()=>{
      setTimeout(()=>{
        try{
          uni.createSelectorQuery()
              .in(this)
              .select("#navBarInMessage")
              .boundingClientRect((res) => {
                this.navBarHeight = res.height;
                console.log(res,"pageMessage");
              }).exec();
        }catch(e){
          console.log(e,"pageMessage 错误的高度获取");
        }

      },50);
    })
    // 接收到消息，将lastMessage更新到列表中
    this.$kt.event.on('FunctionalChatDialogMessage:sendMessage',(lastMessage)=>{
      console.log(lastMessage,"pageMessage收到新消息");
      if(lastMessage && lastMessage.dialogId) {
        this.updateMessageInList(lastMessage);
      }
    });
  },
  created() {
    // 获取列表数据
    this.getInitList();
  },
  methods: {
    scroll(res){
      this.scrollTop = this.$kt.util.pxToRpx(res.target.scrollTop);
    },
    /**
     * 更新消息列表中的消息或添加新对话
     * @param messageData 新消息数据
     */
    async updateMessageInList(messageData) {
      try {
        const dialogId = messageData.dialogId;
        const lastMessage = messageData || {};
        
        // 查找是否已存在此对话
        const existingIndex = this.list.findIndex(item => item.id === dialogId);
        
        if (existingIndex >= 0) {
          // 对话已存在，更新最后一条消息
          const updatedItem = { 
            ...this.list[existingIndex],
            lastMessage: lastMessage,
            lastMessageJsonStr: JSON.stringify(lastMessage)
          };
          
          // 更新对话信息
          const updatedDialog = await this.updateItem(updatedItem);
          
          // 删除旧位置
          this.list.splice(existingIndex, 1);
          // 添加到列表顶部
          this.list.unshift(updatedDialog);
        } else {
          // 对话不存在，获取对话信息并添加到列表
          this.$kt.request.post("/functional-chat-web/dialog/getById", {
            data: { id: dialogId }
          }).then(async (res) => {
            if(res.data) {
              const newDialog = {
                ...res.data,
                lastMessage: lastMessage,
                lastMessageJsonStr: JSON.stringify(lastMessage)
              };
              
              // 完善对话信息
              const updatedDialog = await this.updateItem(newDialog);
              // 添加到列表顶部
              this.list.unshift(updatedDialog);
            }
          });
        }
      } catch(err) {
        console.error("更新消息列表失败", err);
      }
    },
    /**
     * 修改item信息
     */
    updateItem(item){
      return new Promise((resolve, reject)=>{
        let oneToOneIdentifierSplit = item.oneToOneIdentifier.split("&");

        let userAccountId = oneToOneIdentifierSplit[0].split(":")[1];
        if (userAccountId+"" === this.$kt.userAccount.getSelf().id+"") {
          userAccountId = oneToOneIdentifierSplit[1].split(":")[1];
        }
        this.$kt.userAccount.getById(userAccountId).then((res) => {
          console.log(res, "userAccount");
          let lastMessage = {};
          if(item.lastMessage){
            lastMessage = item.lastMessage;
          }else{
            // 最后一条消息
            lastMessage = JSON.parse(item.lastMessageJsonStr || "{}");
            console.log(lastMessage, "lastMessage");
          }
          res.introduction = "";
          try {
            let type = lastMessage.items[0].type;
            let content = lastMessage.items[0].content;
            if (type === "text") {
              res.introduction = content;
            } else if (type.startsWith("image")) {
              res.introduction = "[" + this.$i18n.zhToGlobal("图片") + "]";
            } else if (type.startsWith("userAccount")) {
              res.introduction = "[" + this.$i18n.zhToGlobal("用户名片") + "]";
            }
          } catch (err) {
            reject(err);
          }
          item = {
            ...item,
            userAccount: res,
            lastMessageJsonStr: lastMessage,
          };
          resolve(item);
        });
      }).catch(err=>{
        reject(item);
      })

    },

    getInitList(){
      // /functional-chat-web/dialog/getBySelf
      this.$kt.request.post("/functional-chat-web/dialog/getBySelf", {
        data: {}
      }).then(async (res) => {
        this.list = [];
        let list = res.data;
        console.log(list,"userAccount");
        for (let i = 0; i < list.length; i++) {
          let item = list[i];
          if(!item.oneToOneIdentifier) {
            continue;
          }
          await this.updateItem(item).then((res) => {
            this.list.push(res);
          })

        }
      }).catch(err => {
      });
    }
  }
}
</script>

<template>
<view>
  <view class="bg"></view>
  <view id="navBarInMessage">
    <kt-nav-bar
        ref="navBar"
        :icon="$kt.file.byPath('tabbar/message-selected.svg')"
        :title="$i18n.zhToGlobal('消息')"></kt-nav-bar>
  </view>

  <scroll-view
      :style="'height: calc(100vh - '+navBarHeight+'px - 20rpx - 50rpx)'"
      scroll-y
      @scroll="scroll"
  >
    <view class="box">
      <view style="height: 20rpx"></view>

      <view v-for="(item, index) in list" :key="index"
      @click="$kt.router.navTo('/pages/chat/chat?dialogId='+item.id)"
      >
        <user-info-card
            :user-info="item.userAccount"
        ></user-info-card>
        <u-divider></u-divider>
      </view>

      <view style="height: 100rpx"></view>
    </view>
  </scroll-view>
</view>


</template>

<style scoped lang="scss">
.box {
  padding: 20rpx;
  box-sizing: border-box;
}
//.bg{
//  position: fixed;
//  top: 0;
//  left: 0;
//  width: 100%;
//  height: 100%;
//  z-index: -1;
//  // 从白到黑的渐变，从上到下
//  background: linear-gradient(to bottom, #ffffff 300rpx, #f0f0f0 100%);
//}
</style>
